<template>
  <!-- 添加或修改入库单对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="100%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="采购类别:">
            <el-radio-group v-model="form.goodsType">
              <el-radio
                v-for="dict in dict.type.goods_type"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购日期:" prop="ddDate">
            <el-date-picker clearable
                            v-model="form.ddDate"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="请选择采购日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商:" prop="supplierId">
            <el-select v-model="form.supplierId" placeholder="请选择供应商" filterable @change="selectSupplier"
                       style="width: 260px">
              <el-option v-for="dict in dict.type.goods_supplier" ref="myselectSsupplier"
                         :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="采购类型:" prop="ywType">
            <el-select v-model="form.ywType" placeholder="请选择采购类型" clearable style="width: 180px;">
              <el-option v-for="dict in dict.type.caigou_type"
                         :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="定金:" prop="dingjin">
            <el-input-number v-model="form.dingjin" :precision="2" :min="0" style="width: 260px;"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运费:">
            <el-input-number v-model="form.shippingFee" :precision="2" :min="0" style="width: 260px;"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="form.shippingFee>0">
          <el-form-item label="运费合并付款:">
            <el-radio-group v-model="form.depositMerge">
              <el-radio v-for="dict in dict.type.yes_no"
                        :key="dict.value" :label="dict.value">{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开户行:">
            <el-input v-model="form.bankName" disabled placeholder="请输入开户行"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="银行行号:">
            <el-input v-model="form.bankNo" disabled placeholder="请输入银行行号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="银行账号:">
            <el-input v-model="form.accountNo" disabled placeholder="请输入银行账号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="购买人:">
            <el-input v-model="form.buyer" placeholder="请输入购买人"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注:">
            <el-input v-model="form.remark" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" ref="table"
              :max-height="tableMaxHeight" @sort-change="handleSortChange">
      <el-table-column type="index" label="序号"></el-table-column>

      <el-table-column prop="goodsBrand" label="物料选择" width="380">
        <template slot-scope="scope">
          <el-autocomplete style="width: 350px;"
                           v-model="scope.row.goodsBrand"
                           :fetch-suggestions="querySearch"
                           placeholder="请输入内容"
          >
            <template #default="{ item, index }">
              <div @click="handleClick(item, scope.$index)">
                {{ item.value }}
              </div>
            </template>
          </el-autocomplete>
        </template>
      </el-table-column>
      <el-table-column prop="goodsCode" label="存货编码"/>
      <el-table-column prop="goodsName" label="物料名称"/>
      <el-table-column prop="goodModel" label="物料型号"/>

      <el-table-column label="成品/材料" align="center" key="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.goodsType"
            active-value="1"
            inactive-value="0"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="单价" width="160">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.goodsBuyPrice" @change="updateTotalCost(scope.row)" size="mini"
                           :min="0" :precision="4"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="采购数量" width="160" prop="shengyu" fixed="right">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.shengyu" @change="updateTotalCost(scope.row)" size="mini" :precision="4"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="重量" width="160" prop="dun" fixed="right">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.dun" size="mini" :precision="4"
                           @change="updateTotalCost(scope.row)"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="总价" width="160" prop="goodsBuyTotal" fixed="right">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.goodsBuyTotal" size="mini" :precision="4"
                           @change="updateBuyPriceByTotal(scope.row)"></el-input-number>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100" fixed="right">
        <template slot-scope="scope">
          <el-popconfirm :title="`确认删除当前数据项？`" @confirm="handleDelete(scope.row,scope.$index)"
                         style="margin-left: 10px;">
            <el-button slot="reference" size="mini" type="text" icon="el-icon-delete"
                       v-hasPermi="['develop:GoodsSaleMaterial:remove']">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-row>
      <el-col :span="24" style="text-align: center;padding-top: 20px;">
        <el-button style="width: 100%;" icon="el-icon-plus" plain type="primary" @click="addRow">添加行</el-button>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定 </el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {addAction, deleteAction, getAction, getById, updateAction, isEmpty, accMul} from '@/api/manage';
import moment from 'moment';
import {parseTime} from "@/utils/common";

export default {
  name: "LvRukuOtherListForm",
  dicts: ['goods_customer', 'company', 'yes_no', 'goods_supplier', 'goods_type', 'caigou_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      activeName: "first",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        supplierId: null,
        supplierName: null,
        dingjin: null,
        kaihuhang: null,
        shippingFee: null,
        depositMerge: null,
        zhanghao: null,
        hanghao: null,
        remark: null,
        goodsType: "0",
      },
      type: null,
      dataList: [],
      goodsList: [],
      queryParams: {
        parentId: null,
        pageSizeZero: true,
      },
      goodsQueryParams: {
        name: null,
        pageNum: 1,
        pageSize: 20,
      },
      // 表单校验
      rules: {
        ddDate: [
          {required: true, message: "请选择采购日期", trigger: "blur"}
        ],
        supplierId: [
          {required: true, message: "请选择供应商", trigger: "blur"}
        ],
        bankName: [
          {required: true, message: "请输入开户行", trigger: "blur"}
        ],
        accountNo: [
          {required: true, message: "请输入银行账号", trigger: "blur"}
        ],
        ywType: [
          {required: true, message: "请选择采购类型", trigger: "blur"}
        ],
        depositMerge: [
          {required: true, message: "请选择运费是否合并付款", trigger: "blur"}
        ],
      },
      tableMaxHeight: window.innerHeight - 320,
      url: {
        getById: '/lvRuku/lvRuku/',
        add: '/lvRuku/lvRuku/addWithDetail',
        edit: '/lvRuku/lvRuku/editWithDetail',
        detailList: '/goodsSalebuyall/goodsSalebuyall/list',
        remove: '/goodsSalebuyall/goodsSalebuyall/deleteCg/',
        goodsSupplierById: '/goodsSupplier/goodsSupplier/',
        submitBuySelf: '/goodsSalebuyall/goodsSalebuyall/submitBuySelf',
        updateBuySelf: '/goodsSalebuyall/goodsSalebuyall/updateBuySelf',
      },
    };
  },
  created() {
  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        code: null,
        name: null,
        mainId: null,
        nos: null,
        ddDate: null,
        subDate: null,
        type: null,
        source: "2",
        ywType: null,
        customerId: null,
        customerName: null,
        isBuy: null,
        money: null,
        counts: null,
        dunwei: null,
        supplierId: null,
        supplierName: null,
        deptId: null,
        deptName: null,
        userId: null,
        userName: null,
        state: null,
        rukupeople: this.$store.getters.nickName,
        rukuid: this.$store.getters.userId,
        rukuDate: new Date(),
        status: "1"
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd(type) {
      this.reset();
      this.form.goodsType = "0";
      this.form.ddDate = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
      this.open = true;
      this.title = "添加自采采购单";
      this.dataList = [];
      for (let i = 0; i < 1; i++) {
        this.dataList.push({
          goodsType: '0',//产品类别
          goodsId: '',//产品编号
          goodsCode: '',//产品编号
          goodsName: '',//名称
          goodModel: '',
          daohuoCount: 0
        })
      }
      this.loading = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title="修改自采采购单";
      this.form = row;
      this.open = true;
      this.loading = false;
      this.queryParams.mainId =row.id;
      this.buyId =row.id;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.handleQuery();
    },

    selectSupplier(value) {
      let that = this;
      that.$nextTick(() => {
        let arr = that.$refs.myselectSsupplier;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].currentValue == value) {
            that.form.supplierName = arr[i].label;
            getById(this.url.goodsSupplierById, value).then(response => {
              that.form.bankName = response.data.bankName;//开户行
              that.form.accountNo = response.data.accountNo;//账号
              that.form.bankNo = response.data.bankNo;//行号
              //that.form.supplierId = response.data.id;//id
            });
          }
        }
      })
    },


    getGoodsList() {
      let params = {"pageNum": 1, "pageSize": 20,};
      getAction('/goodsOrderIn/goodsOrderIn/list', params).then(response => {
        this.goodsList = response.rows;
        for (let i = 0; i < this.goodsList.length; i++) {
          // this.goodsList[i].label = this.goodsList[i].name + '-' + this.goodsList[i].model + '-' + this.goodsList[i].code;
          this.goodsList[i].value = this.goodsList[i].name + '-' + this.goodsList[i].model + '-' + this.goodsList[i].code;
        }
      })
    },

    handleClick(item, index) {
      this.$nextTick(() => {
        let newItem = {
          goodsId: item.id,
          goodsCode: item.code, //产品编号
          goodsName: item.name, //名称
          goodModel: item.model,//型号
          goodsUnit: item.unit, // 单位
          goodsBrand: item.brand, // 单位
          count: item.count, // 单位
          goodsType: '0', // 单位
          daohuoCount: "0"
        }
        this.$set(this.dataList, index, newItem)
      })
    },

    /** 查询销售信息管理列表 */
    getList() {
      this.loading = true;
      getAction(this.url.detailList, this.queryParams).then(response => {
        this.dataList = response.rows;
        this.loading = false;
        if (this.dataList.length === 0) {
          for (let i = 0; i < 1; i++) {
            this.dataList.push({
              goodsType: '0',//产品类型
              goodsId: '',//产品编号
              goodsCode: '',//产品编号
              goodsName: '',//名称
              goodModel: '',
              daohuoCount: 0
            })
          }
        } else {
          for (let i = 0; i < this.dataList.length; i++) {
            this.dataList[i].goodsBrand = this.dataList[i].goodsName + '-' + this.dataList[i].goodModel + '-' + this.dataList[i].goodsCode;
          }
        }

      });
    },

    querySearch(queryLabel, cb) {
      let that = this;
      that.goodsQueryParams.queryLabel = queryLabel;
      getAction('/goodsOrderIn/goodsOrderIn/list', that.goodsQueryParams).then(response => {
        that.goodsList = response.rows;
        for (let i = 0; i < this.goodsList.length; i++) {
          that.goodsList[i].value = that.goodsList[i].name + '-' + that.goodsList[i].model + '-' + that.goodsList[i].code;
        }
        const goodsList = that.goodsList;
        const results = queryLabel
          ? goodsList.filter(that.createFilter(queryLabel))
          : goodsList;
        // 调用 callback 返回建议列表的数据
        cb(results);
      })
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().includes(queryString.toLowerCase())
        );
      };
    },
    //点击按钮添加空行
    addRow() {
      this.$nextTick(() => {
        this.dataList.push({
          goodsType: '0',//产品类型
          code: '',//产品编号
          goodsName: '',//名称
          goodModel: '',
          daohuoCount: 0
        })
      })
    },

    /** 提交按钮 */

    submitForm() {
      let that = this;
      let arrays = that.dataList;
      for (let i = 0; i < arrays.length; i++) {
        if (isEmpty(arrays[i].goodsId)) {
          that.$modal.msgError("第" + (i + 1) + "行,请选择产品");
          return;
        }
        if (that.isNumberEqual(arrays[i].goodsBuyPrice, 0) || isEmpty(arrays[i].goodsBuyPrice)) {
          that.$modal.msgError(arrays[i].goodsName + ":产品单价不能为0");
          return;
        }
        if (arrays[i].goodsType === '0') {
          if (that.isNumberEqual(arrays[i].shengyu, 0) || isEmpty(arrays[i].shengyu)) {
            that.$modal.msgError(arrays[i].goodsName + ":请输入采购数量");
            return;
          }
        }
        if (arrays[i].goodsType === '1') {
          if (that.isNumberEqual(arrays[i].dun, 0) || isEmpty(arrays[i].dun)) {
            that.$modal.msgError(arrays[i].goodsName + ":请输入采购重量");
            return;
          }
        }
      }

      that.$refs["form"].validate(valid => {
        if (valid) {
          that.form.goodsSalebuyallList = that.dataList;
          if (that.form.id != null) {
            updateAction(that.url.updateBuySelf, that.form).then(response => {
              that.$modal.msgSuccess("修改成功");
              that.open = false;
              that.$emit('ok');
            });
          } else {
            addAction(that.url.submitBuySelf, that.form).then(response => {
              that.$modal.msgSuccess("新增成功");
              that.open = false;
              that.$emit('ok');
            });
          }
        }
      });
    },


    updateTotalCost(row) {
      let that = this;
      if (row.goodsType === "0") {
        if (row.shengyu && row.goodsBuyPrice) {
          let totleCost = accMul(row.shengyu, row.goodsBuyPrice);
          that.$set(row, "goodsBuyTotal", totleCost);
        }
      }
      if (row.goodsType === "1") {
        if (row.dun && row.goodsBuyPrice) {
          let totleCost = accMul(row.dun, row.goodsBuyPrice);
          that.$set(row, "goodsBuyTotal", totleCost);
        }
      }
    },


    updateBuyPriceByTotal(row) {
      let that = this;
      if (row.goodsType === "0") {
        if (row.shengyu && row.goodsBuyTotal) {
          let totalCost = that.functionCostPriceTax(row.goodsBuyTotal, row.shengyu);
          that.$set(row, "goodsBuyPrice", totalCost);
        }
      }
      if (row.goodsType === "1") {
        if (row.dun && row.goodsBuyTotal) {
          let totalCost = that.functionCostPriceTax(row.goodsBuyTotal, row.dun);
          that.$set(row, "goodsBuyPrice", totalCost);
        }
      }
    },

    handleDelete(row, index) {
      const ids = row.id || this.ids;
      if (isEmpty(ids)) {
        this.$nextTick(() => {
          this.dataList.splice(index, 1)
        })
      } else {
        deleteAction(this.url.remove, ids).then(response => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      }
    },

    isNumberEqual(num1, num2) {
      return Math.abs(num1 - num2) < 0.0001;
    }


  }
};
</script>
<style lang="scss">
.el-form-item__content {
  line-height: 40px !important;
}
</style>
